package utility

import (
	"context"
	"fmt"
	"go_muban/internal/model"
	"go_muban/internal/service"
	neturl "net/url"
	"regexp"
	"strings"

	"github.com/gocolly/colly"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/os/glog"
	"github.com/gogf/gf/v2/text/gstr"
)

const HTTP_PREFIX = "https:"
const MB_BASE_URL = "https://sc.chinaz.com"

// const PROXY_URL = "http://5.78.118.46:60857"
const PROXY_URL = ""

var ctx context.Context

func StartCollect(url string) {
	ctx = context.Background()
	glog.SetPath("./glog")
	// glog.SetStdoutPrint(false)
	glog.SetFile("collect_stdout.log")
	CollectPage(url)
}

// 采集单页
func CollectPage(url string) {
	c := colly.NewCollector()
	if PROXY_URL != "" {
		c.SetProxy(PROXY_URL)
	}
	// var hrefs []string
	var hasNextPage = false

	c.OnHTML(".picblock.box", func(e *colly.HTMLElement) {
		var href = e.ChildAttr("div a", "href")
		var thumb = HTTP_PREFIX + e.ChildAttr("div a img", "src")
		if href != "" {
			CollectDetail(href, thumb)
		}
	})

	c.OnHTML(".nextpage:not(.greys)", func(e *colly.HTMLElement) {
		url = "https://sc.chinaz.com/moban/" + e.Attr("href")
		hasNextPage = true
	})

	glog.Printf(ctx, "采集列表地址: %s", url)

	c.Visit(url)

	WaitShortTime()

	// 采集下一页
	if hasNextPage {
		CollectPage(url)
	}
}

func CollectDetail(url string, thumb string) {
	WaitShortTime()

	if !strings.HasPrefix(url, HTTP_PREFIX) {
		url = HTTP_PREFIX + url
	}

	c := colly.NewCollector()
	if PROXY_URL != "" {
		c.SetProxy(PROXY_URL)
	}
	var mBDetail = new(model.MBDetail)
	mBDetail.SId = GetFlagByUrl(url)
	mBDetail.Id = 0
	mBDetail.Thumb = thumb
	mBDetail.Origin = url
	mBDetail.Images = []string{} // 初始化为空切片

	c.OnHTML(".text_wrap h2 a", func(e *colly.HTMLElement) {
		mBDetail.Title = e.Text
	})

	// 采集主图片
	c.OnHTML(".img_open a", func(e *colly.HTMLElement) {
		imageUrl := HTTP_PREFIX + e.Attr("href")
		mBDetail.Images = append(mBDetail.Images, imageUrl)
	})

	// 采集其他相关图片（如果有的话）
	c.OnHTML(".related_img a", func(e *colly.HTMLElement) {
		if e.Attr("href") != "" {
			imageUrl := HTTP_PREFIX + e.Attr("href")
			// 避免重复添加
			isDuplicate := false
			for _, existingUrl := range mBDetail.Images {
				if existingUrl == imageUrl {
					isDuplicate = true
					break
				}
			}
			if !isDuplicate {
				mBDetail.Images = append(mBDetail.Images, imageUrl)
			}
		}
	})

	c.OnHTML(".img_yl a", func(e *colly.HTMLElement) {
		previewUrl, err := GetIframeSrcFromUrl(MB_BASE_URL + gstr.Trim(e.Attr("href")))
		if err != nil {
			glog.Printf(ctx, "获取预览地址失败: %s", err)
		} else {
			mBDetail.Preview = previewUrl
		}
	})

	c.OnHTML(".img_edit span em", func(e *colly.HTMLElement) {
		mBDetail.Updated = e.Text
	})

	c.OnHTML(".img_edit span a", func(e *colly.HTMLElement) {
		var url = MB_BASE_URL + e.Attr("href")
		mBDetail.FenLei = model.EnHrefItem{
			Title: e.Text,
			Url:   url,
			En:    GetFlagByUrl(url),
		}
	})

	c.OnHTML(".help p > span:first-child", func(e *colly.HTMLElement) {
		mBDetail.FileSize = e.Text
	})

	c.OnHTML(".downbody .dian > a", func(e *colly.HTMLElement) {
		var download = model.HrefItem{
			Title: e.Text,
			Url:   e.Attr("href"),
		}
		mBDetail.Download = append(mBDetail.Download, download)
	})

	c.OnHTML(".gjz_tag .ta_block:first-child .smr > a", func(e *colly.HTMLElement) {
		var url = MB_BASE_URL + e.Attr("href")
		var tag = model.EnHrefItem{
			Title: e.Text,
			Url:   url,
			En:    GetFlagByUrl(url),
		}
		mBDetail.Tags = append(mBDetail.Tags, tag)
	})

	c.OnHTML(".gjz_tag .ta_block:nth-of-type(2) .smr", func(e *colly.HTMLElement) {
		mBDetail.Desc = e.Text
	})

	c.Visit(url)

	// fmt.Printf("%+v\n", mBDetail)
	fmt.Printf("%s | %s | %s\n", mBDetail.SId, mBDetail.Title, mBDetail.Origin)

	service.Template().SaveByMBDetail(gctx.GetInitCtx(), mBDetail)

	WaitShortTime()
}

const RE_MATCH_STR = "/([^/]+)\\.html?$"

func GetFlagByUrl(url string) string {
	re := regexp.MustCompile(RE_MATCH_STR)
	var res = re.FindStringSubmatch(url)
	if len(res) > 1 {
		return res[1]
	}
	return ""
}

// GetIframeSrcFromUrl 从URL获取iframe的src属性并转换为完整地址
func GetIframeSrcFromUrl(url string) (string, error) {
	// 创建一个新的Collector实例
	c := colly.NewCollector(
		colly.UserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"),
	)

	var iframeSrc string
	var found bool

	// 查找iframe标签并获取src属性
	c.OnHTML("iframe", func(e *colly.HTMLElement) {
		if !found {
			src := e.Attr("src")
			if src != "" {
				iframeSrc = src
				found = true
			}
		}
	})

	// 访问URL
	err := c.Visit(url)
	if err != nil {
		return "", err
	}

	// 如果找到iframe的src属性，将其转换为完整URL
	if iframeSrc != "" {
		// 检查是否是相对URL
		if !strings.HasPrefix(iframeSrc, "http://") && !strings.HasPrefix(iframeSrc, "https://") {
			// 解析基础URL
			baseURL, err := neturl.Parse(url)
			if err != nil {
				return "", err
			}

			// 解析相对URL
			relativeURL, err := neturl.Parse(iframeSrc)
			if err != nil {
				return "", err
			}

			// 合并为完整URL
			fullURL := baseURL.ResolveReference(relativeURL)
			iframeSrc = fullURL.String()
		}
		return iframeSrc, nil
	}

	return "", fmt.Errorf("未找到iframe标签或src属性为空")
}
